/**
 * HQLInsertCreator.java
 * 卢晓峰
 * Email：lxf9601@gmail.com
 * QQ：297051898
 * Created by 2010-7-18
 */
package com.autoabacus.core.config.provider.creator;

import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.autoabacus.core.config.component.Field;
import com.autoabacus.core.config.component.Table;
import com.autoabacus.core.config.exception.FieldNotFoundException;
import com.autoabacus.core.config.provider.HQLCreator;
import com.autoabacus.core.config.provider.QuerySource;

/**
 * hql insert语句创建器
 * @author 卢晓峰
 */
public class HQLInsertCreator implements HQLCreator {
	
	public Logger log = LoggerFactory.getLogger(HQLInsertCreator.class);
	public static final String HSQL_TYPE = "insert";
	
	/* (non-Javadoc)
	 * @see com.autoabacus.core.config.provider.HSQLCreator#supports(java.lang.String)
	 */
	@Override
	public boolean supports(String hsqlType) {
		return hsqlType.equals(HSQL_TYPE);
	}

	/* (non-Javadoc)
	 * @see com.autoabacus.core.config.provider.HSQLCreator#getHSQL(com.autoabacus.core.config.Table, com.autoabacus.core.config.provider.QuerySource)
	 */
	@Override
	public String getHQL(Table table, QuerySource querySource) {
		StringBuffer hql = new StringBuffer();
		hql.append("insert into ");
		hql.append(table.getName());
		hql.append("(");
		StringBuffer values = new StringBuffer();
		for (Entry<String, Object> entry : querySource.getParameters().entrySet())
		{
			Field field = table.getFields().get(entry.getKey());
			if (field == null) {
				log.error("字段{}不存在于配置信息中", entry.getKey());
				throw new FieldNotFoundException("字段" + entry.getKey() + "不存在于配置信息中");
			}
			hql.append(field.getName());
			hql.append(",");
			
			values.append(entry.getValue());
			values.append(",");
		}
		
		hql = hql.deleteCharAt(hql.length() - 1);

		hql.append(")");
		hql.append(" values(");
		hql.append(values.deleteCharAt(values.length() - 1));
		hql.append(")");
		
		log.debug(hql.toString());
		return hql.toString();
	}

}
